package br.com.nooclix.salon.application.impl;

import java.util.List;

import br.com.nooclix.salon.application.ServiceApplication;
import br.com.nooclix.salon.domain.SalonException;
import br.com.nooclix.salon.domain.attendance.AttendanceSheetRepository;
import br.com.nooclix.salon.domain.service.Service;
import br.com.nooclix.salon.domain.service.ServiceRepository;

public class ServiceApplicationImpl implements ServiceApplication {

	private ServiceRepository serviceRepository;

	private AttendanceSheetRepository sheetRepository;

	public ServiceApplicationImpl(ServiceRepository serviceRepository,
			AttendanceSheetRepository sheetRepository) {
		super();
		this.serviceRepository = serviceRepository;
		this.sheetRepository = sheetRepository;
	}

	@Override
	public void persist(Service entity) throws Exception {
		if (entity.getName().isEmpty()) {
			throw new SalonException("Por favor, informe o nome do serviço");
		}

		List<Service> list = serviceRepository.list();

		for (Service service : list) {
			if (service.getName().equalsIgnoreCase(entity.getName())) {
				throw new SalonException("Este serviço já esta cadastrado!");
			}
		}

		serviceRepository.persist(entity);
	}

	@Override
	public void update(Service entity) throws Exception {
		if (entity.getName().isEmpty()) {
			throw new SalonException("Por favor, informe o nome do serviço");
		}

		List<Service> list = serviceRepository.list();

		for (Service service : list) {
			if (service.getName().equalsIgnoreCase(entity.getName())) {
				throw new SalonException("Este serviço já esta cadastrado!");
			}
		}

		serviceRepository.update(entity);
	}

	@Override
	public Service findById(Integer id) {
		return serviceRepository.findById(id);
	}

	@Override
	public void delete(Service entity) throws Exception {

		if (serviceRepository.findById(entity.getCode()) == null) {
			throw new SalonException(
					"Atualize sua consulta, pois o serviço de "
							+ entity.getName()
							+ ", provavelmente foi excluido.");
		}

		if (!sheetRepository.findByService(entity).isEmpty()) {
			throw new SalonException(entity.getName()
					+ " não pode ser excluído(a), pois existem "
					+ "comandas de atendimentos referentes a ele(a)!");
		}

		serviceRepository.delete(entity);
	}

	@Override
	public List<Service> list() {
		return serviceRepository.list();
	}

	@Override
	public List<Service> findByName(String name) {
		return serviceRepository.findByNameService(name);
	}

}
